import dayjs from 'dayjs';

function getApiBaseUrl(): string | undefined {
  return import.meta.env.VITE_API_BASE_URL;
}

export async function fetchApi(path: string, method: string = 'GET', body?: any) {
  const baseUrl = getApiBaseUrl() || `${window.location.protocol}//${window.location.host}`;
  const url = `${baseUrl}${path}`;
  console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'),"url is",url);
  const options = {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include' as RequestCredentials,
    body: method !== 'GET' ? JSON.stringify(body) : undefined,
  };
  const response = await fetch(url, options);
  if (!response.ok) throw new Error(`HTTP错误：${response.status}`);
  return response.json();
};